package com.apigen.platform.controller;

import com.apigen.platform.common.Result;
import com.apigen.platform.dto.DatabaseConnectionRequest;
import com.apigen.platform.dto.TableImportRequest;
import com.apigen.platform.service.IDatabaseService;
import com.apigen.platform.vo.DatabaseTableVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 数据库管理控制器
 *
 * @author API Generator Platform
 * @since 2025-09-24
 */
@Slf4j
@RestController
@RequestMapping("/api/database")
@RequiredArgsConstructor
@Validated
@Tag(name = "数据库管理", description = "数据库连接、表结构导入、字段配置等数据库相关接口")
public class DatabaseController {

    private final IDatabaseService databaseService;

    @PostMapping("/test-connection")
    @Operation(summary = "测试数据库连接", description = "测试远程数据库连接是否正常")
    public Result<Map<String, Object>> testConnection(@Valid @RequestBody DatabaseConnectionRequest connectionRequest) {
        try {
            Map<String, Object> result = databaseService.testConnection(connectionRequest);
            return Result.success(result);
        } catch (Exception e) {
            log.error("测试数据库连接失败: {}", e.getMessage());
            return Result.error("测试连接失败: " + e.getMessage());
        }
    }

    @PostMapping("/tables")
    @Operation(summary = "获取数据库表列表", description = "获取指定数据库中的所有表信息")
    public Result<List<DatabaseTableVO>> getDatabaseTables(@Valid @RequestBody DatabaseConnectionRequest connectionRequest) {
        try {
            List<DatabaseTableVO> tables = databaseService.getDatabaseTables(connectionRequest);
            return Result.success(tables);
        } catch (Exception e) {
            log.error("获取数据库表列表失败: {}", e.getMessage());
            return Result.error("获取表列表失败: " + e.getMessage());
        }
    }

    @PostMapping("/tables/{tableName}")
    @Operation(summary = "获取表详细信息", description = "获取指定表的详细结构信息，包括字段、索引等")
    public Result<DatabaseTableVO> getTableDetail(
            @Valid @RequestBody DatabaseConnectionRequest connectionRequest,
            @Parameter(description = "表名") @PathVariable String tableName) {
        try {
            DatabaseTableVO table = databaseService.getTableDetail(connectionRequest, tableName);
            return Result.success(table);
        } catch (Exception e) {
            log.error("获取表详细信息失败: {}", e.getMessage());
            return Result.error("获取表详情失败: " + e.getMessage());
        }
    }

    @PostMapping("/import")
    @Operation(summary = "导入数据表", description = "将远程数据库中的表导入到系统中")
    public Result<Map<String, Object>> importTables(
            @Valid @RequestBody DatabaseConnectionRequest connectionRequest,
            @Valid @RequestBody TableImportRequest importRequest) {
        try {
            Map<String, Object> result = databaseService.importTables(connectionRequest, importRequest);
            return Result.success(result);
        } catch (Exception e) {
            log.error("导入数据表失败: {}", e.getMessage());
            return Result.error("导入表失败: " + e.getMessage());
        }
    }

    @GetMapping("/imported")
    @Operation(summary = "获取已导入的表列表", description = "分页获取已导入到系统中的表列表")
    public Result<Page<DatabaseTableVO>> getImportedTables(
            @Parameter(description = "项目ID") @RequestParam(required = false) Long projectId,
            @Parameter(description = "当前页", example = "1") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "表名筛选") @RequestParam(required = false) String tableName) {
        try {
            Page<DatabaseTableVO> page = databaseService.getImportedTables(projectId, current, size, tableName);
            return Result.success(page);
        } catch (Exception e) {
            log.error("获取已导入表列表失败: {}", e.getMessage());
            return Result.error("获取表列表失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/tables")
    @Operation(summary = "删除已导入的表", description = "批量删除已导入到系统中的表")
    public Result<Void> deleteTables(@Parameter(description = "表ID列表") @RequestBody List<Long> tableIds) {
        try {
            Boolean result = databaseService.deleteTables(tableIds);
            if (result) {
                return Result.success("删除表成功");
            } else {
                return Result.error("删除表失败");
            }
        } catch (Exception e) {
            log.error("删除表失败: {}", e.getMessage());
            return Result.error("删除表失败: " + e.getMessage());
        }
    }

    @PutMapping("/tables/{tableId}")
    @Operation(summary = "更新表信息", description = "更新已导入表的基本信息")
    public Result<Void> updateTableInfo(
            @Parameter(description = "表ID") @PathVariable Long tableId,
            @Parameter(description = "表描述") @RequestParam String tableComment) {
        try {
            Boolean result = databaseService.updateTableInfo(tableId, tableComment);
            if (result) {
                return Result.success("更新表信息成功");
            } else {
                return Result.error("更新表信息失败");
            }
        } catch (Exception e) {
            log.error("更新表信息失败: {}", e.getMessage());
            return Result.error("更新表信息失败: " + e.getMessage());
        }
    }

    @PostMapping("/tables/{tableId}/sync")
    @Operation(summary = "同步表结构", description = "从远程数据库同步表结构到系统中")
    public Result<Map<String, Object>> syncTableStructure(
            @Parameter(description = "表ID") @PathVariable Long tableId,
            @Valid @RequestBody DatabaseConnectionRequest connectionRequest) {
        try {
            Map<String, Object> result = databaseService.syncTableStructure(tableId, connectionRequest);
            return Result.success(result);
        } catch (Exception e) {
            log.error("同步表结构失败: {}", e.getMessage());
            return Result.error("同步表结构失败: " + e.getMessage());
        }
    }

    @GetMapping("/relations")
    @Operation(summary = "获取表关联关系", description = "获取项目中表的关联关系信息")
    public Result<List<Map<String, Object>>> getTableRelations(
            @Parameter(description = "项目ID") @RequestParam Long projectId) {
        try {
            List<Map<String, Object>> relations = databaseService.getTableRelations(projectId);
            return Result.success(relations);
        } catch (Exception e) {
            log.error("获取表关联关系失败: {}", e.getMessage());
            return Result.error("获取关联关系失败: " + e.getMessage());
        }
    }

    @GetMapping("/tables/{tableId}/ddl")
    @Operation(summary = "生成表DDL", description = "生成指定表的DDL创建语句")
    public Result<String> generateTableDDL(@Parameter(description = "表ID") @PathVariable Long tableId) {
        try {
            String ddl = databaseService.generateTableDDL(tableId);
            return Result.success(ddl);
        } catch (Exception e) {
            log.error("生成表DDL失败: {}", e.getMessage());
            return Result.error("生成DDL失败: " + e.getMessage());
        }
    }
}











